<template>
  <van-uploader :max-size="700 * 1024" :max-count="1" :before-read="beforeRead" :after-read="afterRead" accept="image/*">
    <template #default>
        <slot name="default"></slot>
</template>
  </van-uploader>
</template>

<script setup name = "UploaderImage">
  import {
    showFailToast
  } from 'vant';
  function beforeRead(file) {
    if (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg') {
      return true;
    } else {
      showFailToast('请上传正确格式的图片');
      return false;
    }
  }
  function blobToBase64(blob){
    return new Promise((resolve,reject)=>{
      const reader = new FileReader();
      reader.readAsDataURL(blob.file);
      reader.onload=()=>{
        const base64 = reader.result;
        resolve(base64);
      }
      reader.onerror = error => reject(error);
    })
  }
  function afterRead(file) {
    console.log('%c [ file ]-43', 'font-size:13px; background:pink; color:#bf2c9f;', file);
    blobToBase64(file).then((base64Image) => {
    console.log('Base64 Image:', base64Image); 
    // 调用传入的回调函数，将base64Image作为参数传递给它  
    // onBase64Image(base64Image);   
    })   
  }
// // 接收父组件传入的回调函数  
// const onBase64Image = defineEmits(['base64-image'])[0]; 

</script>

<style>

</style>
